#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.const import RepositoryDataTypeEnum
from common.logger import Logger
from common.parse_parafile import ParamFileUtil, get_env_variable
from db2.comm.const import Db2JsonConstant
from db2.comm.util.common_util import Db2CommonUtil

LOGGER = Logger().get_logger(filename="db2.log")


class ParameterBackupParse:
    def __init__(self, p_id, job_id, sub_job_id, json_param):
        self._p_id = p_id
        self._job_id = job_id
        self._sub_job_id = sub_job_id
        self._repositories_path = ""
        self._meta_path = ""
        self._json_param = json_param

    def get_repositories_path(self, repository_type):
        """
        从参数中获取仓的位置
        1: 数据仓: 存放备份副本
        2：cache仓: 存放临时文件
        3：日志仓： 日志备份
        4：meta仓： 元数据，存放恢复时需要的文件
        :return:
        """
        if not self._json_param:
            LOGGER.error(f'Get cache path failed, reasons: json_param is NUll, pid: {self._p_id} '
                         f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
            return ""
        job_json = self._json_param.get(Db2JsonConstant.JOB, {})
        repositories_json = job_json.get(Db2JsonConstant.REPOSITORIES, [])
        for item in repositories_json:
            if item.get(Db2JsonConstant.REPOSITORY_TYPE, "") == repository_type:
                self._repositories_path = item.get(Db2JsonConstant.PATH, [""])[0]
                LOGGER.info(f'Get path success, path: {self._repositories_path}, pid: {self._p_id} '
                            f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
                Db2CommonUtil.check_path_list(self._repositories_path)
                return self._repositories_path

        # 在query job permission请求时不存在这写请求数据
        LOGGER.debug(f'Get path failed, reasons: get from param failed, pid: {self._p_id} '
                     f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
        return ""

    def get_repositories_all_date_path(self) -> list:
        """
        :return: 全部的数据仓库
        """
        if not self._json_param:
            LOGGER.error(f'Get cache path failed, reasons: json_param is NUll, pid: {self._p_id} '
                         f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
            return []
        job_json = self._json_param.get(Db2JsonConstant.JOB, {})
        repositories_json = job_json.get(Db2JsonConstant.REPOSITORIES, [])
        for item in repositories_json:
            if item.get(Db2JsonConstant.REPOSITORY_TYPE, "") == RepositoryDataTypeEnum.DATA_REPOSITORY.value:
                all_date_path = item.get(Db2JsonConstant.PATH, [])
                LOGGER.info(f'Get path success, path: {self._repositories_path}, pid: {self._p_id} '
                            f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
                Db2CommonUtil.check_path_list(*all_date_path)
                return all_date_path
        # 在query job permission请求时不存在这写请求数据
        LOGGER.error(f'Get all date path failed, reasons: get from param failed, pid: {self._p_id} '
                     f'taskid: {self._job_id} subTaskId: {self._sub_job_id}')
        return []

    def get_backup_database_name(self):
        """
        获取待备份的数据库名称
        """
        db_name = self._json_param.get(Db2JsonConstant.JOB, {})\
            .get(Db2JsonConstant.PROTECT_OBJECT, {}).get(Db2JsonConstant.NAME)
        Db2CommonUtil.check_injection(db_name)
        return db_name
    
    def get_sanclient_type(self):
        """
        获取是否为sanclient备份
        """
        sanclient_type = self._json_param.get(Db2JsonConstant.JOB, {})\
            .get(Db2JsonConstant.EXTEND_INFO, {}).get(Db2JsonConstant.SANCLIENT_TYPE, "false")
        return sanclient_type
    
    def get_ts_backup_database_name(self):
        """
        获取待备份表空间的数据库名称
        """
        db_name = self._json_param.get(Db2JsonConstant.JOB, {})\
            .get(Db2JsonConstant.PROTECT_OBJECT, {}).get(Db2JsonConstant.PARENT_NAME)
        Db2CommonUtil.check_injection(db_name)
        return db_name

    def get_backup_type(self):
        """
        获取备份类型
        """
        return self._json_param.get(Db2JsonConstant.JOB, {}).get(Db2JsonConstant.JOB_PARAM, {}). \
            get(Db2JsonConstant.BACKUP_TYPE)

    def get_sub_job_name(self):
        """
        获取备份子任务名称
        """
        return self._json_param.get(Db2JsonConstant.SUB_JOB, {}). \
            get(Db2JsonConstant.JOB_NAME)

    def get_copy_rep_info(self, backup_type):
        """
        获取下发的副本仓信息
        """
        return ParamFileUtil.get_rep_info(self._json_param.get("job"), backup_type)

    def get_database_user_name(self, database_user_name_key):
        key = database_user_name_key + "_" + str(self._p_id)
        user_name = get_env_variable(key)
        return user_name

    def get_applications(self):
        return self._json_param.get("job", {}).get("protectObject")

    def get_nodes_list(self):
        return self._json_param.get("job", {}).get("protectEnv", {}).get("nodes", [])

    def get_now_nodes_user_name(self):
        now_agent_id = Db2CommonUtil.get_agent_id()
        nodes_list = self.get_nodes_list()
        node_index = 0
        for nodes in nodes_list:
            if now_agent_id == nodes.get("id", ""):
                break
            node_index += 1
        return self.get_database_user_name(f"job_protectEnv_nodes_{node_index}_auth_authKey")

    def get_delete_log(self):
        return self._json_param.get(Db2JsonConstant.JOB, {}).get(Db2JsonConstant.EXTEND_INFO, {}). \
            get(Db2JsonConstant.DELETE_LOG, "false")

    def get_json_param(self):
        return self._json_param
    